package org.boyan.modules.controller;

import com.alibaba.fastjson.JSON;
import org.boyan.common.api.vo.Result;
import org.boyan.modules.service.TransService;
import org.boyan.modules.service.WSDLService;
import org.boyan.modules.vo.TransVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/wsdl")
public class WSDLController {
    @Value("${boyan.path.upload}")
    private String uploadPath;

    @Autowired
    private WSDLService wsdlService;

    @Autowired
    private TransService transService;

    @PostMapping("/generate")
    public Result wsdl(@RequestBody Map<String,Object> map){
        TransVO transVO= JSON.parseObject(JSON.toJSONString(map.get("transVo")),TransVO.class);
        String path= (String) map.get("path");
        if(wsdlService.runWsdl(uploadPath+"/shell/startWsdl.sh"+" "+transVO.getTransCode()+" "+path.trim())){
            //修改交易状态
            transService.changeTransStatus(4,transVO.getTransCode());
            return Result.OK("WSDL框架代码生成成功");
        }else{
            return Result.error("WSDL框架代码生成失败");
        }
    }

    @GetMapping("/download/{transCode}")
    public void download(@PathVariable("transCode")String transCode, HttpServletResponse response){
        String path=uploadPath+"/wsdl/"+transCode;
        if(wsdlService.runWsdl(uploadPath+"/shell/zipWsdl.sh"+" "+uploadPath+"/wsdl/"+transCode+" "+path)){
            String filePath=uploadPath+"/wsdl/"+transCode+".zip";
            File file=new File(filePath);
            try {
                FileInputStream in=new FileInputStream(file);
                OutputStream output=response.getOutputStream();
                int len=0;
                byte[] b=new byte[1024];
                //将Content-Disposition暴露出来
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(transCode+".zip","UTF-8"));
                while((len=in.read(b))!=-1){
                    output.write(b,0,len);
                }
                output.flush();
                output.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
